<template>
    <view>
        <view class="popup" v-if="goodsinfo.goods_id>0">
            <!-- 头部商品开始 -->
            <view class="topGoods">
                <view class="Pic">
                    <image mode="aspectFill" class="goodsImage" :src="goodsinfo.cover_url"></image>
                </view>
                <view class="goodsInfo">
                    <view class="goodsName moreText">{{goodsinfo.name}}</view>
                    <view class="goodsDescription">{{$t('stock')}}:{{goodsinfo.stock_num}}</view>
                    <view class="goodsData" v-if="goodsinfo.sku_arr.list.length>0">
                        <view class="monthlySales">
                            <text>{{$t('selected')}}:</text>
                            <text class="clickWord">{{xz_sku_name}}</text>
                        </view>
                    </view>
                    <view class="bottomOperation">
                        <view class="retailPrice">
                            <view class="price">{{goodsinfo.price}}</view>
							<view class="price fuhao"> {{siteInfo.money.unit}}</view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 头部商品结束 -->
            <!-- 商品规格开始 -->
				<scroll-view scroll-y class="tui-popup-scroll">
					<view class="tui-scrollview-box">
						<template v-for="(item,index) of goodsinfo.sku_arr.tree">
							<view class="tui-bold tui-attr-title">{{item.k}}</view>
							<view class="tui-attr-box">
								<view :class="parseInt(goodsinfo.sku_arr.initialSku['s'+(index+1)])==parseInt(i.id)?'tui-attr-item-active':'tui-attr-item'" v-for="(i,j) of item.v"
								 @click="xz_sku_cs('s'+(index*1+1),i.id)">
									<view class="guige_03_01">
										{{i.name}}
									</view>
								</view>
							</view>
						</template>
                    <!-- 数量 -->
                    <view class="u-flex">
                        <view class="u-flex-m" style="font-size: 28rpx;">{{$t('num')}}</view>
						<view class="numberBox u-flex">
						    <u-number-box :value="num" :min="1" :max="goodsinfo.goods_type==1?1:goodsinfo.stock_num" @change="sku_change_num"></u-number-box>
						</view>
                        <!-- <view style="width: 220rpx;">
                            <u-number-box v-model="num" :min="1" :max="specGoodsData.totalStockCount" @plus="plus" @minus="minus"></u-number-box>
                        </view> -->
                    </view>
					</view>
				</scroll-view>
            <!-- 商品规格结束 -->
            <!-- 确定按钮 -->
            <view class="determine" v-if="popupType==2">
                <button @click="onPurchase(goodsinfo,'')" size="default" type="primary" class="button" :style="{background:PrimaryColor}">{{buyName}}</button>
            </view>
            <view class="determine u-flex" v-else-if="popupType==3">
                <button @click="onDetermine(goodsinfo,'')" size="default" type="primary" class="button u-flex-m" style="background:#ffa63a;margin:0 10rpx;">{{$t('addtocart')}}</button>
                <button @click="onDetermine(goodsinfo,'onPurchase')" size="default" type="primary" class="button u-flex-m" style="margin:0 10rpx;" :style="{background:PrimaryColor}">{{buyName}}</button>
            </view>
            <view class="determine" v-else>
                <button @click="onDetermine(goodsinfo,'')" size="default" type="primary" class="button" :style="{background:PrimaryColor}">{{$t('addtocart')}}</button>
            </view>
            <!-- tabbar占位高度 -->
            <view :style="{height: systemInfo.titleBarHeight+'rpx'}"></view>
        </view>
    </view>
</template>

<script>
	import { mapState, mapMutations } from 'vuex';
	import base from '@/config/baseUrl.js';
	import { isNumber } from 'util';
	export default {
		props:{
            isPopup: {
                type: Boolean
            },
			cart: {
				type: Array,
				default(){
					return []
				}
			},
			goodsinfo: {
				type: Object,
				default(){
					return []
				}
			},
            //规格状态 1：默认 加入购物车 2：不加人购物车 按钮名称改成去购买 配合isAuto=true使用 3:显示加入购物车按钮、去购买按钮
            popupType: {
                type: [Number,String],
                default(){
                	return 1;
                }
            },
            //是否显示数量控件 false：隐藏 true：显示
            isShowNum: {
                type: Boolean,
                default(){
                	return true;
                }
            },
		},
		computed:{
		    ...mapState(['PrimaryColor','siteInfo']),
		},
        data() {
            return {
				systemInfo:base.systemInfo,
                freeSpecsButtonBackground:'rgba(254,70,29,.1)',
                showPopup: false,
                addNumber:1,
                disabled:true,//是否禁止规格数量控件 true：禁止
                buyName:this.$t('buynow'),
                current:0,//选择的规格
                selArray:'',//已选规格属性
				num:1,
				sku_arr: '',
				xz_sku_name : this.$t('selectspeci'),
				sku_index:'',
				sku_id:'',
            };
        },
        watch:{
            isPopup(val){
                console.log('isPopup',val)
            },
        },
        created() {

        },
        methods:{
            //选择属性/规格
            onfreeSpecs(e,index){
                this.current = index
                this.selArray = e
                var item = {
                    type:1,//1:选择规格 2：加入购物车 3：去购买 4:输入的数量
					selArray:e
                }
                this.$emit('change',item)
            },
            // 加入购物车
            onDetermine(e,go) {
				const that = this
				let cart = this.cart
				if (!this.check_sku()) {
					return;
				}
				
				const cart_count = Object.keys(this.cart).length
				
				if (cart_count==0){cart=[]}
				let index=0
				if (cart_count>0){
					index = cart.findIndex(item => {
						if(this.goodsinfo.sku_id>0) {
							return (item.id === parseFloat(this.goodsinfo.goods_id)) && (item.sku_id === this.goodsinfo.sku_id)
						} else {
							return item.id === parseFloat(this.goodsinfo.goods_id)
						}
					})
				}
				if(index > -1&&cart_count!=0) {
						cart[index].num = this.num
				} else {
						let order_arr = this._setOrderData()
						if (!order_arr)return
						cart.push(order_arr)
				}	
                var item={
                    type:2,//1:选择规格 2：加入购物车 3：去购买 4:输入的数量
					goods:e,
                    num:this.num,
					cart:cart
                }
				console.log('加入购物车',item)
                this.$emit('change',item)
				
				//将规格重置，否则进行直接购买时直接点击会报错。
				for (let [k, v] of Object.entries(this.goodsinfo.sku_arr.tree)) {
					this.goodsinfo.sku_arr.initialSku[v.k_s] = ''
				}
				if(go=='onPurchase'){
					//加入并直奔购物车
					this.$tools.goJump('/pages/goods/cart',{},'','')
				}else{
					uni.$u.toast(this.$t('success'))
				}
				
            },
            //去购买
            onPurchase(e){
				if (!this.check_sku()) {
					return;
				}
				
				//const arr = this._setOrderData() //组合数据
				//if (!arr) {
				//	return;
				//}
				//console.log('add_shopping',arr)
				//const id = arr['goods_id'];
				//放缓存
				//let cart = []
				//let cart = this.cart
				//cart.push(arr)
				//uni.setStorageSync('buy', cart)
				//uni.setStorageSync('cartStorage', cart)

				//this.$tools.goJump('/pages/goods/cart',{state:'buy'},'','')
				
            },
			//检查规格是否都已选择
			check_sku() {
				const that = this
				if (this.goodsinfo.sku_arr.list.length < 1) {
					return true
				}
				let isku = this.goodsinfo.sku_arr.initialSku
				for (let [k, v] of Object.entries(isku)) {
					if (v == '') {
						uni.$u.toast(this.$t('selectspeci'))
						return false
					}
				}
				return true
			},
			//组合数据
			_setOrderData() {
				const that = this
				const goods = this.goodsinfo
				let arr = {};
				
				if (this.goodsinfo.sku_arr.list.length < 1) {
					// if (goods.stock_num == 0 || goods.stock_num ==null) {
					// 	this.$tools.msg('库存不足')
					// 	return false;
					// }
					if(parseFloat(goods.stock_num)>0){}else{
							this.$tools.msg(this.$t('lowstock'))
							return false;
					}
					
					arr['sku_id'] = goods.sku_id
					arr['sku_name'] = ''
				}else{
					const sku=goods.sku_arr.list[this.sku_index]
					// if (sku.stock_num == 0 || sku.stock_num == null) {
					// 	this.$tools.msg('库存不足')
					// 	return false;
					// }
					if(parseFloat(sku.stock_num)>0){}else{
							this.$tools.msg(this.$t('lowstock'))
							return false;
					}
					
					arr['sku_id'] = sku.sku_id
					arr['sku_name'] = sku.specname
				}

				console.log('goods',goods)
				if(parseFloat(goods.price)>0){
					arr['id'] = goods.goods_id
					arr['goods_id'] = goods.goods_id
					arr['goods_name'] = goods.name
					arr['cover_url'] = goods.cover_url ? goods.cover_url : ''
					arr['price'] = goods.price
					arr['goods_type'] = goods.goods_type
					arr['num'] = this.num
					arr['category_id'] = goods.category_id
					
				// if (this.siteInfo.site.order_group=='brand'){
				// 	arr['group_id'] = goods.brand_info.brand_id
				// 	arr['group_name'] = goods.brand_info.name
				// }else if(this.siteInfo.site.order_group=='shop'){
				//   if (this.shop_id==''){
				// 	  this.$tools.msg('设置为店铺分组模式但确少shopid,无法下单。');return false;
				//   }
				//   arr['group_id'] = this.shop_id
				//   arr['group_name'] = ''
				// }else{
				  arr['group_id'] = ""
				  arr['group_name'] = ""
				

					
					console.log('arr:', arr)
					return arr
				}else{
					this.$tools.msg(this.$t('priceerr'))
					return false;
				}
			},
			//切换规格图片
			change_sku_img(id) {
				let g = this.goodsinfo.sku_arr.tree[0].v
				for (let [k, v] of Object.entries(g)) {
					if (id == v.id && v.imgUrl) {
						this.goodsinfo.cover_url = v.imgUrl
					}
				}
			},
			
			//数量选择
			sku_change_num(e) {
				const detail = e.value
				let g = this.goodsinfo
				if (g.sku_arr.list.length > 0) {
					g.sku_arr.initialSku.selectedNum = detail
				} else {
					g.sku_arr.initialSku = {}
					g.sku_arr.initialSku.selectedNum = detail
				}
				console.log('num2:', detail)
				this.goodsinfo = g,
				this.num = detail
			},
			//选择规格-显示价格
			xz_sku_cs(ik, iv) { 
				let g = this.goodsinfo
				let isku = g.sku_arr.initialSku
				isku[ik] = iv //选中了的1-3级规格  initialSku  
				this.change_sku_img(iv)

				let count = Object.keys(isku).length - 1 //有几级规格
				let price = g.price
				let stock_num = g.stock_num
				let sku_name = ''
				let sku_index = -1
				let sku_id=''
				for (let [k, v] of Object.entries(g.sku_arr.list)) {
					if (count == 1) {
						if (isku['s1'] == v['s1']) {
							price = v.price_sales
							stock_num = v.stock_num
							sku_name = v['s1_name']
							sku_id = v['sku_id']
							sku_index = k
						}
					}
					if (count == 2) {
						if (isku['s1'] == v['s1'] && isku['s2'] == v['s2']) {
							price = v.price_sales
							stock_num = v.stock_num
							sku_name = v['s1_name'] + ' ' + v['s2_name']
							sku_index = k
							sku_id = v['sku_id']
						}
					}
					if (count == 3) {
						if (isku['s1'] == v['s1'] && isku['s2'] == v['s2'] && isku['s3'] == v['s3']) {
							price = v.price_sales
							stock_num = v.stock_num
							sku_name = v['s1_name'] + ' ' + v['s2_name'] + ' ' + v['s3_name']
							sku_index = k
							sku_id = v['sku_id'] 
						}
					}
				}
				g.price = parseFloat(price)
				g.stock_num = stock_num
				g.sku_name = sku_name
				g.sku_id = sku_id
				this.xz_sku_name = g.sku_name
				this.goodsinfo = g,
				this.sku_index = sku_index
				this.sku_id = sku_id
			},
            
        }
	}
</script>

<style lang="scss">

.u-flex-m {
    -webkit-box-flex: 1;
    -webkit-flex: 1;
    flex: 1;
    overflow: hidden
}
.moreText {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}
.popup {
    background: #fff;
    border-radius: 16rpx 16rpx 0 0;
}
/* 头部商品开始 */
.topGoods {
    overflow: hidden;
    position: relative;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    /* border-bottom: 1px solid #f5f5f5; */
    padding: 40rpx 40rpx 24rpx 40rpx;
    box-sizing: border-box;
    .Pic {
        width: 136rpx;
        height: 136rpx;
        .goodsImage {
            width: 136rpx;
            height: 136rpx;
            border-radius: 10rpx;
        }
    }
    .goodsInfo {
        margin-left: 20rpx;
        width: 100%;
        .goodsName {
            font-size: 32rpx;
            font-weight: bold;
            padding-right: 35rpx;
        }
        .goodsDescription {
            color: #999;
            font-size: 22rpx;
            line-height: 24rpx;
            margin-top: 10rpx;
            display: inline-block;
            white-space: nowrap;
            width: 490rpx;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .goodsData {
            /* #ifndef APP-NVUE */
            display: flex;
            /* #endif */
            flex-direction: row;
            // margin-top: 4rpx;
            text {
                color: #666;
                font-size: 24rpx;
            }
            .monthlySales {
                margin-right: 20rpx;
                .clickWord {
                    max-width: 300rpx;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
            }
        }
        .bottomOperation {
            /* #ifndef APP-NVUE */
            display: flex;
            /* #endif */
            flex-direction: row;
            margin-top: 10rpx;
            align-items: center;
            .retailPrice {
                /* #ifndef APP-NVUE */
                display: flex;
                /* #endif */
                flex-direction: row;
                align-items: flex-end;
                color: #fe461d;
                margin-right: 24rpx;
            }
        }
    }
}

.determine {
    padding: 20rpx 40rpx;
    background: #fff;
    .button {
        padding: 0rpx 44rpx;
        height: 90rpx;
        line-height: 90rpx;
        border-radius: 45px;
        background: #65b05b;
        border: none;
    }
}

	.tui-popup-scroll {
		max-height: calc(100vh - 360px);
		font-size: 26upx;
	}

	.tui-scrollview-box {
		padding: 0 30upx 60upx 30upx;
		box-sizing: border-box;
	}

	.tui-attr-title {
		padding: 10upx 0;
		color: #333;
	}

	.tui-attr-box {
		font-size: 0;
		padding: 20upx 0;
	}

	.tui-attr-item {
		max-width: 100%;
		min-width: 200upx;
		height: 64upx;
		display: -webkit-inline-flex;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		background: #f7f7f7;
		padding: 0 26upx;
		box-sizing: border-box;
		border-radius: 32upx;
		margin-right: 20upx;
		margin-bottom: 20upx;
		font-size: 26upx;
	}

	.tui-attr-item-active {
		max-width: 100%;
		min-width: 200upx;
		height: 64upx;
		display: -webkit-inline-flex;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		background: #f7f7f7;
		padding: 0 26upx;
		box-sizing: border-box;
		border-radius: 32upx;
		border: 1px solid #E54D42;
		margin-right: 20upx;
		margin-bottom: 20upx;
		font-size: 26upx;
		color: #E54D42;
	}

	.tui-attr-active {
		background: #fcedea !important;
		color: #e41f19;
		font-weight: bold;
		position: relative;
	}

	.tui-attr-active::after {
		content: "";
		position: absolute;
		border: 1upx solid #e41f19;
		width: 100%;
		height: 100%;
		border-radius: 40upx;
		left: 0;
		top: 0;
	}

</style>
